package com.ptu.spzx.manager.filter;


import com.alibaba.fastjson.JSON;
import com.ptu.spzx.manager.utils.RedisCache;
import com.ptu.spzx.model.vo.common.Result;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import com.ptu.spzx.security.pojo.LoginUser;
import com.ptu.utils.JwtUtil;
import com.ptu.utils.WebUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;


@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        //解析token获取其中的userId
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //token超时
            e.printStackTrace();
            Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        String userId = claims.getSubject();
        System.out.println("=======");
        System.out.println(userId);
        LoginUser loginUser = redisCache.getCacheObject("user:login"+userId);
        if (Objects.isNull(loginUser)) {
            //用户不存在，登录过期，提示重新登录
            Result<Object> result = Result.build(null, ResultCodeEnum.TOKEN_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        //存入securityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request, response);
    }


//    @Override
//    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//
//    }
}
